﻿using System.Windows;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;
using SD.Libs.Navigation.Contracts;

namespace SD.Libs.Navigation
{
    public class PropagateNavContextToVMBehavior : Behavior<PhoneApplicationPage>
    {
        protected override void OnAttached()
        {
            base.OnAttached();

            // Let's hook to PageLoaded
            // on pageLoaded we assume the Datacontext is available (VM)
            // we try to cast to our INavigationContext interface and fire
            // the navigation event including the navigation context info (query string parameters)
            this.AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
        }

        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            PhoneApplicationPage currentPage = this.AssociatedObject;

            // The DataContext will contain the VM let's try to cast it
            // to INavigationContext andfire the navigation event including the context information
            if (currentPage.DataContext != null)
            {
                INavigationContext vmNavContext = currentPage.DataContext as INavigationContext;

                if (vmNavContext != null)
                {
                    vmNavContext.NotifyNavigated(currentPage.NavigationContext.QueryString);
                }
            }
        }
        
    }
}
